package syb.wind.speed.direction.plugin;

import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import io.netty.buffer.ByteBuf;
import syb.wind.speed.direction.plugin.model.SpeedDirectionStoreEntry;

public class SpeedDirectionDevice extends ModbusNumDevice<SpeedDirectionStoreEntry> {
    public SpeedDirectionDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (engine, factory, centerFacilities, entity);
    }

    @Override
    public SpeedDirectionStoreEntry decode(ModemResponseMessage msg) {
        logger.info("start syb speed direction decode");
        ByteBuf buf = msg.getData();
        int speed = buf.readUnsignedShort ();
        int windLevel = buf.readUnsignedByte ();
        int directionAngle = buf.readUnsignedShort ();
        int direction = buf.readUnsignedByte ();
        SpeedDirectionStoreEntry entry = new SpeedDirectionStoreEntry();
        entry.setSpeed (String.format ("%.1f",speed/10.0f));
        entry.setWindLevel (String.format ("%.1f",windLevel/10.0f));
        entry.setDirectionAngle ( String.format ("%.1f",directionAngle/10.0f));
        entry.setDirection ( getDirection (direction));
        logger.info ("{}[{}]",this.entity.getName (),entry);
        return entry;
    }


    private String getDirection(int direction){
        return direction==0?"北"
                :direction==1?"北东北"
                :direction==2?"东北"
                :direction==3?"东东北"
                :direction==4?"东"
                :direction==5?"东东南"
                :direction==6?"东南"
                :direction==7?"南东南"
                :direction==8?"南"
                :direction==9?"南西南"
                :direction==10?"西南"
                :direction==11?"西西南"
                :direction==12?"西"
                :direction==13?"西西北"
                :direction==14?"西北"
                :direction==15?"北西北":"未知风向";
    }
    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData().readableBytes()== 8;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory().getRequestMessage(getConfig());
    }

    @Override
    protected void disposable() {

    }
}
